<template>
  <span>{{ timeStr }}</span>
</template>

<script>
var _this;
export default {
  data() {
    return {
      isEnd: false,
      spanStr: "",
      currentTimestamp: 0,
      promiseTimer: "",
    };
  },
  props: {
    remainTime: {
      // 倒计时间总秒数
      default: 0,
    },
  },
  mounted() {
    // if (this.remainTime > 0) {
    //   this.currentTimestamp = this.remainTime;
    //   this.countDowm();
    // }
  },
  methods: {
    initTimer() {
      if (this.remainTime > 0) {
        this.currentTimestamp = this.remainTime;
        this.countDowm();
      }
    },
    // 倒计时
    countDowm() {
      this.promiseTimer = setInterval(function () {
        _this.currentTimestamp = _this.currentTimestamp - 1000;
      }, 1000);
    },
    // 删除计时器
    deleteTimer() {
      console.log("delete timer");
      clearInterval(this.promiseTimer);
      _this.currentTimestamp = 0;
      Object.assign(this.$data, this.$options.data());
    },
    // 格式化
    format(num) {
      return num.toString().padStart(2, "0");
    },
  },
  computed: {
    timeStr() {
      var time = _this.currentTimestamp;
      var h = Math.floor(time / 1000 / 60 / 60);
      var m = Math.floor((time / 1000 / 60) % 60);
      var s = Math.floor((time / 1000) % 60);
      if (h > 0) {
        return _this.format(h) + " : " + _this.format(m) + " : " + _this.format(s);
      } else {
        return _this.format(m) + " : " + _this.format(s);
      }
    },
  },
  created() {
    _this = this;
  },
  watch: {
    currentTimestamp(val, oldVal) {
      if (val <= 0) {
        _this.isEnd = true;
        _this.deleteTimer();
        _this.$emit("endTimer");
      }
    },
  },
};
</script>
